#include <handy/handy.h>
#include "s3010.h"
#include "motor.h"
#include <wiringPi.h>
#include <softPwm.h>
#include <iostream>
#include <regex>

using namespace std;
using namespace handy;

#define PORT 8081
int threads = 1;
MultiBase base(threads);
HttpServer sample(&base);
S3010 servo;
MOTOR motor;

/** 
* 命令分发
*/
void cmdBranch() {
    // 请求链接为http://192.168.0.171:8081/servo?76 | http://192.168.0.171:8081/servo?-76
    sample.onGet("/sever", [](const HttpConnPtr &con) {
        string v = con.getRequest().version;

        cout << "Request:" << con.getRequest().uri << endl;
        string query_uri = con.getRequest().query_uri, uri = con.getRequest().uri;
        string param = query_uri.substr(uri.length() + 1);

        servo.pwmSet(stoi(param));
        string body = "Request uri: " + uri + "\n" + "Request query_uri: " + query_uri + "\n" + "params: " + param + "\n";
        HttpResponse resp;
        resp.body = Slice(body);
        con.sendResponse(resp);
        if (v == "HTTP/1.0") {
            con->close();
        }
    });

    sample.onGet("/motor", [](const HttpConnPtr &con) {
        string v = con.getRequest().version;

        string query_uri = con.getRequest().query_uri, uri = con.getRequest().uri;
        string param = query_uri.substr(uri.length() + 1);
        motor.speedSet(stoi(param));

        HttpResponse resp;
        resp.body = Slice("hello world1");
        con.sendResponse(resp);
        if (v == "HTTP/1.0") {
            con->close();
        }
    });

    sample.onGet("/stop", [](const HttpConnPtr &con) {
        string v = con.getRequest().version;

        motor.speedSet(0);

        HttpResponse resp;
        resp.body = Slice("hello world2");
        con.sendResponse(resp);
        if (v == "HTTP/1.0") {
            con->close();
        }
    });

    sample.onGet("/return", [](const HttpConnPtr &con) {
        string v = con.getRequest().version;
        HttpResponse resp;
        resp.body = Slice("hello world2");
        con.sendResponse(resp);
        if (v == "HTTP/1.0") {
            con->close();
        }
    });
}

void init() {
    wiringPiSetup();
    servo.init();
    motor.init();
}

int main(int argc, const char *argv[]) {
    if (argc > 1) {
        threads = atoi(argv[1]);
    }
    // setloglevel("TRACE");

    int r = sample.bind("", PORT);
    exitif(r, "bind failed %d %s", errno, strerror(errno));
    init();
    cmdBranch();
    Signal::signal(SIGINT, [&] { base.exit(); });
    base.loop();
    return 0;
}